$(function () {
    var queryUrl = '../modulereplacepart/list';
    var param = '';
    var Id = getQueryString("Id");
    if (Id) {
        param += 'Id=' + Id;
    }
    modulCode = getQueryString("modulCode");
    if (modulCode) {
        param += (param.length > 0 ? '&' : '') + 'modulCode=' + modulCode;
    }
    if (param.length > 0) {
        queryUrl += '?' + param;
    }
    $("#jqGrid").Grid({
        url: queryUrl,
        colModel: [
            {
                label: '换件类别', name: 'typeMethod', index: 'TYPE_METHOD', width: 70,
                formatter: function (value, col, row) {
                    return sysEnums.MODULE_TICKET_TYPE[row.typeMethod];
                }
            },
            {label: '模具号', name: 'moduleNo', index: 'MODULE_NO'},
            {label: '备件名称', name: 'fittingName', index: 'FITTING_NAME', width: 80},
            {label: '位置号', name: 'positionNo', index: 'POSITION_NO', width: 80},
            {label: '类型', name: 'type', index: 'TYPE', width: 80},
            {
                label: '更换时间', name: 'replaceDate', index: 'REPLACE_DATE', width: 100, formatter: function (value) {
                    return transDate(value, 'yyyy-MM-dd hh:mm');
                }
            },
            {label: '寿命标准', name: 'lifeStandard', index: 'LIFE_STANDARD', width: 80},
            {label: '使用次数', name: 'realUseTime', index: 'REAL_USE_TIME', width: 80},
            {label: '型芯条码', name: 'uniqueCode', index: 'UNIQUE_CODE', sortable: false,
                formatter: function (value, col, row) {
                    if(value){
                        return value;
                    }
                    return "<button class='btn btn-outline btn-info' id='recordsText' onclick='vm.associateSP(\"" + row.id + "\")'>&nbsp;关联</button>";
                }
            },
            {label: '备注', name: 'remark', index: 'REMARK', width: 120},
            {label: '创建人', name: 'createUserName', index: 'CREATE_USER', width: 80},
            {
                label: '当前进度', index: 'PROGRESS', width: 80,
                formatter: function (value, col, row) {
                    return sysEnums.MOLD_REPAIR_PROGRESS[row.progress];
                }
            },
            {
                label: '审核详情', name: 'devCode', index: 'DEV_CODE', width: 80, sortable: false,
                formatter: function (value, col, row) {
                    return "<button class='btn btn-outline btn-info' id='recordsText' onclick='vm.showReviewDetail(\"" + escape(JSON.stringify(row)) + "\")'>&nbsp;详情</button>";
                }
            },
            {name: 'progress', hidden: true},
            {name: 'moduleCode', hidden: true},
            {label: 'id', name: 'id', index: 'ID', key: true, hidden: true}
        ]
    });
});

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        moduleReplacePart: {
            typeMethod: '',
            replaceCode: '', // 工单编码,显示用
            remark: '',
            type: '', // 更换备件类型
            lifeStandard: '',
            useTime: '', // 使用模次
            realUseTime: '', // 实际使用次数
            replaceDate: '',
            fittingName: '',
            modulePositionId: '',
            moduleCode: '',
            moldId:'',
            id: ''
        },
        ruleValidate: {
            replaceCode: [
                {required: true, message: '模具编码不能为空', trigger: 'change'}
            ],
            fittingName: [
                {required: true, message: '模具位置必选', trigger: 'change'}
            ]
        },
        q: {
            moduleNo: '',
            name: ''
        },
        // 审核参数VO
        approveParam: {
            approveIdList: [],
            status: 1,
            remark: ''
        },
        moldTicketTypeList: enumsToList('MODULE_TICKET_TYPE')
    },
    methods: {
        deptCheck: function () {
            var _this = this;
            var data = getSelectedRowData('#jqGrid');
            if (data.progress != 1) {
                alert('只有处于[部门审核]的换件记录才可以执行该操作！');
                return;
            }
            // 构建审批参数
            _this.approveParam = {
                approveIdList: [data.id],
                status: '1',
                remark: ''
            }
            openWindow({
                title: '审核模具换件信息',
                area: ['500px', '260px'],
                content: jQuery("#reviewLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    Ajax.request({
                        url: '../modulereplacepart/review',
                        params: JSON.stringify(_this.approveParam),
                        contentType: "application/json",
                        type: 'POST',
                        successCallback: function (res) {
                            alert('审核成功!');
                            setTimeout(function () {
                                location.reload();
                            }, 1000);
                        }
                    });
                }
            });
        },
        // 关联模具型芯
        associateSP: function (recordId) {
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 扫码型芯',
                content: '../module/modulereplacepart_addSP.html',
                area: ['60%', '50%'],
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var moldSpUsedRecord = iframeWin.getMoldSpUsedRecord();
                    // 执行入库操作
                    Ajax.request({
                        url: "../modulereplacepart/associateMoldSpStock",
                        params: {'replacePartRecordId': recordId, 'stockId': moldSpUsedRecord.sparePartsId},
                        type: "POST",
                        successCallback: function (r) {
                            // 关闭当前页面
                            layer.close(index);
                            vm.reload();
                        }
                    });
                }
            });
        },
        //审核详情
        showReviewDetail: function (res) {
            var data = JSON.parse(unescape(res))
            Ajax.request({
                url: '../sysProcess/approve',
                params: {bussinessId: data.id},
                type: 'POST',
                successCallback: function (res) {
                    var approveProcessList = res.approveProcessList;
                    if (approveProcessList.length == 0) {
                        iview.Message.error("暂无审批记录");
                        return;
                    }
                    var dom = "<div class='details'><table>";
                    for (var i = 0; i < approveProcessList.length; i++) {
                        var approveProcess = approveProcessList[i];
                        dom += '<tr><td>' + approveProcess.approveDate + '</td>';
                        dom += '<td align="left">' + approveProcess.roleName + '-' + approveProcess.name + '： ' + sysEnums.CHECK_FLAG[approveProcess.status];
                        if (approveProcess.remark) {
                            dom += '<br />备注：' + approveProcess.remark;
                        }
                        dom += '</td></tr>'
                    }
                    dom += '</table></div>'
                    layer.open({
                        type: 1,
                        title: "审核详情",
                        closeBtn: 0,
                        area: ['500px'],
                        offset: '10vh',
                        shadeClose: true,
                        skin: 'yourclass',
                        content: dom
                    });
                }
            });
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.moduleReplacePart = {
                typeMethod: 1,
                replaceCode: '', // 工单/模具编码,显示用
                remark: '',
                type: -1,  // 需要回填
                replaceDate: getCurrentTime(),
                moduleCode: modulCode,
                moduleNo: '',
                moldId:'',
                id: '',
                moldPositionList: [] // 模具位置列表
            };
        },
        resetForm: function () {
            // 当修改工单类别时重置表单
            //  vm.moduleReplacePart.replaceCode = '';
            //  vm.moduleReplacePart.moduleCode = '';
            //  vm.moduleReplacePart.moduleNo = '';
            //  vm.moduleReplacePart.replaceCode = '';
        },
        update: function (event) {
            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.getInfo(id);
        },
        saveOrUpdate: function (event) {
            var url;
            if (vm.moduleReplacePart.id == (null || '')) {
                url = "../modulereplacepart/save";
                // 获取需要更换的模具位置列表
                var moldPositionList = getSelectedRows('#moldPositionTable');
                if (!moldPositionList || moldPositionList.length == 0) {
                    iview.Message.error("请选择需要更换的模具位置!");
                    return;
                }
                vm.moduleReplacePart.moldPositionList = moldPositionList;
            } else {
                url = "../modulereplacepart/update";
            }
            if (vm.moduleReplacePart.replaceDate) {
                vm.moduleReplacePart.replaceDate = vm.GMT2Str(vm.moduleReplacePart.replaceDate);
            }
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.moduleReplacePart),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        del: function (event) {
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }
            var dataList = getSelectedRowDatas('#jqGrid');
            for (var i = 0; i < dataList.length; i++) {
                if (dataList[i].progress == 5) {
                    layer.alert('只可以删除未通过审核的记录！', {icon: 5});
                    return;
                }
            }
            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../modulereplacepart/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../modulereplacepart/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.moduleReplacePart = r.moduleReplacePart;
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            var param = {};
            if (vm.q.moduleNo) {
                param.moduleNo = vm.q.moduleNo;
            }
            if (vm.q.name) {
                param.name = vm.q.name;
            }
            // 清空postData缓存数据
            var postData = $("#jqGrid").jqGrid("getGridParam", "postData");
            $.each(postData, function (k, v) {
                delete postData[k];
            });
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: param,
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        GMTToDate: function (time) {
            var date = new Date(time)
            return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
        },
        reloadSearch: function () {
            vm.q = {
                moduleNo: '',
                name: ''
            };
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        review: function () { //审核
            var result = getSelectedRowData("#jqGrid");
            var id = result.id;
            if (id == null) {
                return;
            }
            if (result.reviewStatus === "未审核") {
                vm.getInfo(id);
                confirm('确定要审核选中的记录？', function () {
                    vm.moduleReplacePart.reviewStatus = 1;
                    Ajax.request({
                        url: '../modulereplacepart/review',
                        params: JSON.stringify(vm.moduleReplacePart),
                        type: "POST",
                        contentType: "application/json",
                        successCallback: function (r) {
                            alert('操作成功', function (index) {
                                vm.reload();
                            });
                        }
                    });
                });
            } else {
                alert('本记录已审核!');
            }
        },
        getModuleArchives: function () {
            if (!this.moduleReplacePart.typeMethod) {
                iview.Message.error("请选择工单类别后在执行该操作!");
                return;
            }
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 请选择工单关联模具',
                content: '../module/moduleArchiveSelectInTicket.html?typeMethod=' + this.moduleReplacePart.typeMethod,
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getModuleArchives();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        if (res.ticketNo) {
                            vm.moduleReplacePart.replaceCode = res.ticketNo;
                        } else {
                            vm.moduleReplacePart.replaceCode = res.moduleCode;
                        }
                        vm.moduleReplacePart.moduleCode = res.moduleCode;
                        vm.moduleReplacePart.moduleNo = res.moduleNo;
                        vm.moduleReplacePart.moldId = res.moldId;
                        layer.close(index);
                    }
                }
            })
        },
        getSpare: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-bars"></i> 选择模具位置',
                content: '../module/modulposition.html?moduleCode=' + vm.moduleReplacePart.moduleCode,
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getSelectedRowData("#jqGrid");
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        vm.moduleReplacePart.fittingName = res.positionName;
                        vm.moduleReplacePart.type = res.modType;
                        vm.moduleReplacePart.lifeStandard = res.lifeStandard;
                        vm.moduleReplacePart.useTime = res.currentTime;
                        vm.moduleReplacePart.realUseTime = res.currentTime;
                        vm.moduleReplacePart.modulePositionId = res.id;
                        layer.close(index);
                    }
                }
            })
        },
        GMT2Str: function (gmt) {
            var dateTime = new Date(gmt)
            var month = dateTime.getMonth() + 1
            return dateTime.getFullYear() + '-' + month + '-' + dateTime.getDate() + ' ' + dateTime.getHours() + ':' + dateTime.getMinutes() + ':33';
        }
    },
    watch: {
        'moduleReplacePart.moldId': function (newVal, oldVal) {
            if (oldVal) {
                var queryUrl = '../modulpositioncorrelation/list?moldId=' + newVal;
                $("#moldPositionTable").jqGrid('setGridParam', {datatype: 'json', url: queryUrl}).trigger('reloadGrid');
            } else if (newVal) {
                $("#moldPositionTable").Grid({
                    url: '../modulpositioncorrelation/list?moldId=' + newVal,
                    pager: null,
                    width: '100%',
                    rowNum: 150,
                    loadComplete: function (data) {
                        if (data.page.totalCount == 0) {
                            // 清空历史无记录标识
                            $(".norecords").remove();
                            $("#moldPositionTable").parent().append("<pre class='norecords'><div style='margin:10px;color:red;font-size:16px;'>当前模具暂未设置关联位置，请更换！</div></pre>");
                            return;
                        }
                    },
                    colModel: [
                        {label: 'id', name: 'id', index: 'ID', key: true, hidden: true},
                        {label: '备件名称', name: 'positionName', index: 'POSITION_NAME', width: 120},
                        {label: '位置号', name: 'positionNo', index: 'POSITION_NO', width: 70},
                        {label: '规格', name: 'spec', index: 'SPEC', width: 80},
                        {label: '特殊处理', name: 'positionRemark', index: 'POSITION_REMARK'},
                        {label: '类型', name: 'modType', index: 'MOD_TYPE', width: 60},
                        {label: '换件数', name: 'setNum', index: 'SET_NUM', width: 60},
                        {label: '寿命标准', name: 'lifeStandard', index: 'LIFE_STANDARD', width: 60},
                        {
                            label: '最近一次更换时间',
                            name: 'changeTime',
                            index: 'CHANGE_TIME',
                            width: 100,
                            formatter: function (value) {
                                return transDate(value, "yyyy-MM-dd hh:mm");
                            }
                        },
                        {label: '剩余寿命', name: 'residualLife', index: 'RESIDUAL_LIFE', width: 60},
                        {
                            label: '当前次数', index: 'CURRENT_TIME', width: 60,
                            formatter: function (value, col, row) {
                                var stan = row.lifeStandard;
                                var currentTime = row.currentTime;
                                if (currentTime == null || currentTime == "" || stan == null || stan == "") {
                                    return 0;
                                }
                                var ys = stan * 0.8;
                                if (currentTime < ys) {
                                    return currentTime;
                                } else if (currentTime >= ys && currentTime <= stan) {
                                    return '<span style="color: orange">' + currentTime + '</span>';
                                } else {
                                    return '<span style="color: red">' + currentTime + '</span>';
                                }
                            }
                        },
                        {name: 'currentTime', hidden: true}
                    ]
                });
            }
        }
    }
});
